/* C++ */
#include "dsqlite.hh"

static int printinfo_callback(void *data, int argc, char **argv, char **azColName){
	int i;
	printf("%s: \r\n", (const char*)data);
	for(i=0; i<argc; i++){
		printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
	}
	printf("\n");
	return 0;
}


dsqlite::dsqlite(string name) {
	int ret = 0;
	sqlite3_open(name.data(), &db);
	
	if (ret){
		printf("Can't open database: %s\n", sqlite3_errmsg(db));
		return;
	} else {
		printf("Opened database successfully\n");
	}  
}

dsqlite::~dsqlite() {
	sqlite3_close(db);
	printf("db done!\r\n");
}

int dsqlite::add(sqldata* data,int count) {
	int ret = 0;
	char *zErrMsg = 0;
	string  sql;
	sqlite3_stmt *stmt;
	sql = "INSERT INTO Faceinfo VALUES " + trans(data);
	//cout << sql << '\n';

    ret = sqlite3_prepare(db,sql.c_str(),-1,&stmt,NULL);
    if( ret != SQLITE_OK ){
		fprintf(stderr, "err sqlite3_prepare: %s ,rc %d\n", sqlite3_errmsg(db) ,ret);
		return 0;
	}

    ret = sqlite3_bind_blob(stmt, 1, data->data.feature, data->data.featureSize, NULL);   
    if( ret != SQLITE_OK ){
		fprintf(stderr, "err sqlite3_bind_blob: %s ,rc %d\n", sqlite3_errmsg(db) ,ret);
		return 0;
	}

    ret = sqlite3_step(stmt);
    if( ret != SQLITE_DONE ){
		fprintf(stderr, "err sqlite3_step: %s ,rc %d\n", sqlite3_errmsg(db) ,ret);
		return 0;
	}

	sqlite3_finalize(stmt);

	return 0;
}

int dsqlite::del(int id) {
	int ret = 0;
	char *zErrMsg = 0;
	string  sql;
	sql = "DELETE from Faceinfo where ID=" + to_string(id) + ";" ;
	ret = sqlite3_exec(db, sql.c_str(), NULL, NULL, &zErrMsg);
	
	if( ret != SQLITE_OK ){
		printf("SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
	} else {
		printf("DEL Operation done successfully\n");
	}

	return 0;
}

int dsqlite::info(void) {
	int ret = 0;
	char *zErrMsg = 0;
	const char* cdata = "Info Callback function called";
	string  sql;
	sql = "SELECT * from Faceinfo";
	ret = sqlite3_exec(db, sql.c_str(), printinfo_callback, (void*)cdata, &zErrMsg);
	
	if( ret != SQLITE_OK ){
		printf("SQL error: %s\n", zErrMsg);
		sqlite3_free(zErrMsg);
	} else {
		printf("Info Operation done successfully\n");
	}

	return 0;
}

string dsqlite::trans(sqldata * data) {
	string output = "(";
	output = output + to_string(data->id) + ",";
	output = output + "\'" + data->name + "\'," \
			+ "\'" + data->imgpath + "\'" + ",? );";
	return output;
}


int main(){
	const char* save = "hello work!";
	sqldata data = {6,"daijh","aaaa",{(unsigned char*)save,(signed int)strlen(save)}};
	dsqlite * sq = new dsqlite("blob.db");
	sq->info();
	sq->add(&data,1);
	//sq->del(data.id);
	delete sq;
	return 0;
}
